package cn.com.yusys.yusp.message.service.message.channel.impl;


import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.yusys.yusp.message.service.message.channel.EmailSendInterface;
import cn.com.yusys.yusp.message.service.message.channel.impl.DefaultEmailSendImpl;

@Service
public class EmailSendService {
	private Logger logger = LoggerFactory.getLogger(EmailSendService.class);

	
	@Autowired
	private List<EmailSendInterface> emailSendInterface;
	
	private EmailSendInterface getEmailSend(){
		if(emailSendInterface.size()>1){
			for(EmailSendInterface send:emailSendInterface){
				if(send instanceof DefaultEmailSendImpl){
					
				}else{
					return send;
				}
			}
		}
		return emailSendInterface.get(0);
	}
	
	/**
	 * 发送邮件，含附件
	 * @param toEmail 【必填】 目标邮箱
	 * @param title 【必填】 标题 
	 * @param content 【必填】 内容
	 * @param attachment 
	 * @param attachmentName 
	 * @return 成功返回0,不成功返回1
	 */
	public int sendHtmlEmailWithAttachment(String toEmail, String title, String content, Map<String,byte[]> attachments, Short sendNum) {

		int result = 0;
		try {
			result = getEmailSend().sendMessage(toEmail, title, content, attachments);
		} catch (Exception e) {
			result = 1;
		}
		
		if (result == 0) {
			return 0;
		} else {
			logger.error("This is the first time the email failed to be sent");			
		}

		for (int i = 0; i < sendNum; i++) {
			try {
				result = getEmailSend().sendMessage(toEmail, title, content, attachments);
			} catch (Exception e) {
				result = 1;
			}
			if (result == 0) {
				return 0;
			} else {				
				logger.error("This is the [" + (i + 1) + "]th time that resend email fails");
			}
		}
		return 1;
	}
	
}